﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace TestRenameInDomain
{
    public class NativeCode
    {
        internal const uint NETSETUP_ACCT_CREATE = 2;
        protected String m_exception = null;

        public String ErrorMessage
        {
            get
            {
                return m_exception;
            }
        }

        [DllImport("netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        internal static extern int NetRenameMachineInDomain(
            string lpOldMachineName,
            string lpNewMachineName,
            string lpAccount,
            string lpPassword,
            uint fRenameOptions
            );

        public Boolean renameMachineByWin32(String oldName, String newName, String m_domain_admin, String m_domain_admin_password)
        {
            int error = 0;
            Boolean successFlag = true;

            try
            {
                error = NetRenameMachineInDomain(oldName, newName, m_domain_admin, m_domain_admin_password, NETSETUP_ACCT_CREATE);
                if (error != 0)
                {
                    successFlag = false;
                }
            }
            catch (Exception ex)
            {
                successFlag = false;
                m_exception = ex.ToString();
            }

            return successFlag;

        }


    }
}
